<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="小区编号" prop="communityId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.communityId"-->
      <!--          placeholder="请输入小区编号"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="小区名称" prop="communityName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.communityName"-->
      <!--          placeholder="请输入小区名称"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->

      <el-form-item label="小区名称" prop="communityId">

        <el-select v-model="queryParams.communityId" filterable placeholder="请选择小区" style="width: 100%;"
                   @change="handleCommunityChange">
          <el-option
            v-for="item in communityListOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--buildingListOptions-->

      <el-form-item label="楼栋单元" prop="buildingId">
        <!--        <el-select v-model="queryParams.buildingId" placeholder="请选择楼栋编号" clearable>-->
        <!--          <el-option-->
        <!--            v-for="dict in dict.type.biz_nuclein_check_status"-->
        <!--            :key="dict.value"-->
        <!--            :label="dict.label"-->
        <!--            :value="dict.value"-->
        <!--          />-->
        <!--        </el-select>-->

        <el-select v-model="queryParams.buildingId" filterable placeholder="请选择楼栋单元" style="width: 100%;">
          <el-option
            v-for="item in buildingListOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

      </el-form-item>

      <el-form-item label="房间号码" prop="roomNum">
        <el-input
          v-model="queryParams.roomNum"
          placeholder="请输入房间号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="住户姓名" prop="holderName">
        <el-input
          v-model="queryParams.holderName"
          placeholder="请输入住户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="住户性别" prop="holderSex">
        <el-select v-model="queryParams.holderSex" placeholder="请选择住户性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="holderPhoneNum">
        <el-input
          v-model="queryParams.holderPhoneNum"
          placeholder="请输入住户手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号码" prop="holderPhoneIdcardNum">
        <el-input
          v-model="queryParams.holderPhoneIdcardNum"
          placeholder="请输入住户身份证号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:household:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:household:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:household:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:household:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:household:list']"
        >模拟扫码(上传图片)
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="householdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="小区编号" align="center" prop="communityId"/>-->
      <el-table-column label="小区名称" align="center" prop="communityName" width="150"/>
      <!--      <el-table-column label="楼栋编号" align="center" prop="buildingId">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.biz_nuclein_check_status" :value="scope.row.buildingId"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="单元号" align="center" prop="unitNum" width="100"/>
      <el-table-column label="楼栋号" align="center" prop="floorNum" width="100"/>
      <el-table-column label="房间号" align="center" prop="roomNum" width="100"/>
      <el-table-column label="住户姓名" align="center" prop="holderName" width="100"/>
      <!--      <el-table-column label="住户性别" align="center" prop="holderSex" />-->
      <el-table-column label="住户性别" align="center" prop="holderSex" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.holderSex"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="holderPhoneNum" width="120"/>
      <el-table-column label="证件号码" align="center" prop="holderPhoneIdcardNum" width="200"/>
      <el-table-column label="备注" align="center" prop="remark" width="50" />
<!--      width="200"-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"   width="200" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:household:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:household:remove']"
          >删除
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-grid"
            @click="handleQrCode(scope.row.id)"
            v-hasPermi="['system:household:list']"
          >演示二维码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改住户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="编号" prop="id">-->
        <!--          <el-input v-model="form.id" placeholder="请输入编号"/>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="小区编号" prop="communityId">-->
        <!--          <el-input v-model="form.communityId" placeholder="请输入小区编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="小区名称" prop="communityName">-->
        <!--          <el-input v-model="form.communityName" placeholder="请输入小区名称" />-->
        <!--        </el-form-item>-->

        <el-form-item label="小区名称" prop="communityName">
          <el-select v-model="form.communityId" filterable placeholder="请选择小区" style="width: 100%;"
                     @change="handleCommunityChange2">
            <el-option
              v-for="item in communityListOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="楼栋编号" prop="buildingId">
          <!--          <el-select v-model="form.buildingId" placeholder="请选择楼栋编号">-->
          <!--            <el-option-->
          <!--              v-for="dict in dict.type.biz_nuclein_check_status"-->
          <!--              :key="dict.value"-->
          <!--              :label="dict.label"-->
          <!--              :value="dict.value"-->
          <!--            ></el-option>-->
          <!--          </el-select>-->

          <el-select v-model="form.buildingId" filterable placeholder="请选择楼栋单元" style="width: 100%;"
          @change="handleBuildingChange">
            <el-option
              v-for="item in buildingListFormOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="房间号" prop="roomNum">
          <el-input v-model="form.roomNum" placeholder="请输入房间号"/>
        </el-form-item>
        <el-form-item label="住户姓名" prop="holderName">
          <el-input v-model="form.holderName" placeholder="请输入住户姓名"/>
        </el-form-item>
        <el-form-item label="住户性别" prop="holderSex">
          <el-select v-model="form.holderSex" filterable placeholder="请选择住户性别" clearable style="width: 100%;">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="holderPhoneNum">
          <el-input v-model="form.holderPhoneNum" placeholder="请输入住户手机号码"/>
        </el-form-item>
        <el-form-item label="证件号码" prop="holderPhoneIdcardNum">
          <el-input v-model="form.holderPhoneIdcardNum" placeholder="请输入住户身份证号码"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--展示二维码图片的对话框-->
    <el-dialog
      title="二维码演示"
      :visible.sync="dialogVisible"
      width="20%"
>
<!--      <span>这是一段信息</span>-->
      <vue-qr :correctLevel="3" :autoColor="false" colorDark="#313a90"
              style="margin: auto;"
              :text="qrCodeUrl" :size="200" :margin="0" :logoMargin="3">

      </vue-qr>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
import {
  listHousehold,
  getHousehold,
  delHousehold,
  addHousehold,
  updateHousehold,
  getBulidingMapList, getEncodeQrCodeInfo
} from "@/api/system/household";
import {commonMapList} from "@/api/system/common";
import VueQr from 'vue-qr';

export default {
  name: "Household",
  dicts: ['biz_nuclein_check_status', 'sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 住户表格数据
      householdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        communityId: null,
        communityName: null,
        buildingId: null,
        unitNum: null,
        floorNum: null,
        roomNum: null,
        holderName: null,
        holderSex: null,
        holderPhoneNum: null,
        holderPhoneIdcardNum: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //小区信息对应的下拉框参数
      communityListOptions: [],
      //楼栋单元号对应的下拉框参数
      buildingListOptions: [],
      //楼栋单元号对应的下拉框参数(表单模块专用)
      buildingListFormOptions: [],
      //显示二维码图片的弹出框
      dialogVisible:false,
      //加密后的二维码地址
      qrCodeUrl:null
    };
  },
  created() {
    this.getList();
    //获取所有小区
    this.getAllCommunity();
    //获取所有楼栋信息(根据小区id) 测试id为 1618134634178134016
    //this.getAllBuilding('1618134634178134016');
  },
  methods: {
    /**
     * 生成二维码(前端)
     */
    handleQrCode(userId){
      getEncodeQrCodeInfo(userId)
      .then(response=>{
        if(response.code){
          this.dialogVisible = true;
          // 从配置文件中获取baseUrl
          let baseUrl = process.env.VUE_APP_BASE_API;
          let data = response.data;
          let userId = data.userId;
          let taskId = data.taskId;
          //拼接url
          //TODO 此处应该优化,不应该拼接字符串,服务器地址和端口应该从配置文件中读取
          let prefixUrl = "http://192.168.1.165:80";
          this.qrCodeUrl =prefixUrl+ baseUrl+"?userId="+userId+"&taskId="+taskId;

        }
      })
    },
    /** 小区下拉框发生变化,用于获取小区名称,并且联动获取该小区对应的楼栋信息 **/
    handleCommunityChange(key) {
      // console.log(value);
      // console.log(event);
      //首先需要置空表头查询参数 楼栋id
      let that = this;
      this.queryParams.buildingId = null;
      this.buildingListOptions = [];
      let options = this.communityListOptions;
      let list = options.filter(item => item.value === key);
      if (list.length === 1) {
        let currentCommunity = list.pop();
        //this.form.communityName = currentCommunity.label;
        console.log(this.form);
        //this.getAllBuilding(currentCommunity.value);
        getBulidingMapList(currentCommunity.value)
          .then(response => {
            console.log(response);
            if (response.code) {
              that.buildingListOptions = response.data;
            }
          }).catch(err => {
          console.log(err);
        });
      }
    },
    //用于form
    handleCommunityChange2(key) {
      // console.log(value);
      // console.log(event);
      //首先需要置空form中的 楼栋id
      //this.queryParams.buildingId = null;
      let that = this;
      this.form.buildingId = null;
      //还需要置空楼层的options
      this.buildingListFormOptions = [];
      // 根据小区id在前端查询出小区名称
      let options = this.communityListOptions;
      let list = options.filter(item => item.value === key);
      if (list.length === 1) {
        let currentCommunity = list.pop();
        this.form.communityName = currentCommunity.label;
        console.log(this.form);
        //this.getAllBuilding(currentCommunity.value);
        getBulidingMapList(currentCommunity.value)
          .then(response => {
            console.log(response);
            if (response.code) {
              that.buildingListFormOptions = response.data;
            }
          }).catch(err => {
          console.log(err);
        });
      }
    },
    /**表单中的楼栋change事件**/
     handleBuildingChange(key){
      // 根据楼栋id在前端查询出单元号和单元号
      let buildingOptions = this.buildingListFormOptions;
      // console.log(key);
      // console.log(typeof key);
      // console.log(buildingOptions);
      //TODO 无法正常打印出过滤后的数组 疑似使用了弹栈导致变量提升
      let list = buildingOptions.filter(item => item.value === key);
      // console.log("form-楼栋change")
      // console.log(list);
      if (list.length === 1) {
        let currentBuilding = list.pop();
        this.form.floorNum = currentBuilding.floorNum;
        this.form.unitNum = currentBuilding.unitNum;
        console.log(this.form);
      }
    },

    /** 查询所有**/
    //获取所有小区(用于下拉框)
    getAllCommunity() {
      commonMapList({
        tableName: 'biz_community',
        keyName: 'id',
        valueName: 'community_name'
      })
        .then(response => {
          console.log(response);
          if (response.code) {
            this.communityListOptions = response.data;
          }
        }).catch(err => {
        console.log(err);
      });
    },

    /** 查询所有楼栋**/
    //获取所有楼栋(用于下拉框)
    // getAllBuilding(id) {
    //
    // },
    /** 查询住户列表 */
    getList() {
      this.loading = true;
      listHousehold(this.queryParams).then(response => {
        this.householdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        communityId: null,
        communityName: null,
        buildingId: null,
        unitNum: null,
        floorNum: null,
        roomNum: null,
        holderName: null,
        holderSex: null,
        holderPhoneNum: null,
        holderPhoneIdcardNum: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加住户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHousehold(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改住户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHousehold(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHousehold(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除住户编号为"' + ids + '"的数据项？').then(function () {
        return delHousehold(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/household/export', {
        ...this.queryParams
      }, `household_${new Date().getTime()}.xlsx`)
    }
  },components: {
    VueQr
  }
};
</script>
